package org.example;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")  // 应用于所有 URL 路径
public class LoginFilter implements Filter {

    // 定义不需要登录就能访问的路径
    private static final List<String> EXCLUDED_URLS = Arrays.asList("/login", "/register", "/public");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化逻辑
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false); // 获取当前会话，如果没有则返回 null
        String path = httpRequest.getRequestURI(); // 获取请求的路径

        // 检查请求路径是否在排除列表中
        if (isExcludedPath(path)) {
            chain.doFilter(request, response); // 如果是排除路径，允许通过
            return;
        }

        // 检查用户是否已登录
        if (session != null && session.getAttribute("user") != null) {
            chain.doFilter(request, response); // 如果用户已登录，允许请求继续
        } else {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login"); // 如果未登录，重定向到登录页面
        }
    }

    @Override
    public void destroy() {
        // 过滤器销毁逻辑
    }

    // 检查请求路径是否在排除列表中
    private boolean isExcludedPath(String path) {
        return EXCLUDED_URLS.stream().anyMatch(path::startsWith);
    }
}
